﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Booky.Common;
using Booky.WinFormsClient;
using DataStorage;
using Microsoft.VisualBasic.ApplicationServices;
using Newtonsoft.Json;

namespace BookyDesktop
{
    public class SingleInstanceController : WindowsFormsApplicationBase
    {
        public SingleInstanceController()
        {
            // Set whether the application is single instance
            this.IsSingleInstance = true;

            this.StartupNextInstance += new
              StartupNextInstanceEventHandler(this_StartupNextInstance);
        }

        void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
        {
            // Here you get the control when any other instance is
            // invoked apart from the first one.
            // You have args here in e.CommandLine.
            //e.CommandLine[1]
            
            if(e.CommandLine.Any() && e.CommandLine.Count > 1)
            {
                //FileStream f = File.OpenRead();
                string sPath = e.CommandLine[1];

                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(sPath))
                {
                    //StringBuilder s = new StringBuilder();
                    string s = "";
                    string t = "";

                    while ((s = sr.ReadLine()) != null)
                    {
                        t += s;
                    }

                    BookmarkJson o = JsonConvert.DeserializeObject<BookmarkJson>(t);
                    Repository r = new Repository();
                    if(r.IsAuthenticated())
                    {
                        Bookmark b = new Bookmark();
                        b.Name = o.Title ?? "";
                        b.Description = "";
                        b.CreatedDate = DateTime.Now;
                        b.Url = o.Url ?? "";

                        OwnerForm.InsertBookmarkToListControl(b);

                        r.InsertBookmarkLocalCloud(o.Title, o.Url, "");
                    }
                }
            }

            
            // You custom code which should be run on other instances
        }

        public MainForm OwnerForm
        {
            get
            {
                return (MainForm)this.MainForm;
            }
        }

        protected override void OnCreateMainForm()
        {
            // Instantiate your main application form
            this.MainForm = new MainForm();
        }
    }
}
